﻿using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Windows.Forms;

namespace AutoUpdate
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// https://github.com/JackQChen/AutoUpdate
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            MessageBoxEx.time = args.Length == 0 ? 0 : 5000;
            bool createdNew = false;
            Mutex instance = new Mutex(true, Application.ExecutablePath.Replace("\\", "/"), out createdNew);
            if (createdNew)
            {
                UpdateCheck check = new UpdateCheck();
                var localVerCode = Convert.ToInt32(ConfigurationManager.AppSettings["VerCode"]);
                var updateInfo = check.GetUpdateInfo();

                var frm = new FrmMain();
                //无参启动不更新时间
                frm.updateInfo = updateInfo;

                if (!File.Exists(updateInfo.MainProgramName))
                {
                    frm.IsUpdate = false;
                }               

                var remoteVerCode = updateInfo.VerCode;
                var needUpdate = localVerCode < remoteVerCode;
                if (needUpdate  || !File.Exists(updateInfo.MainProgramName))
                {
                    Application.Run(frm);
                }

                MessageBoxEx.Show("自动更新完成!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                if (!frm.IsUpdate && !string.IsNullOrWhiteSpace(updateInfo.InstallProgramName)) 
                {
                    Process.Start(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, updateInfo.InstallProgramName));
                }
                else
                {
                    //启动主程序           
                    Process.Start(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, updateInfo.MainProgramName));
                }               
            }
            else
            {
                MessageBoxEx.Show("自动更新正在运行中!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        /// <summary>
        /// 用批处理功能更新自身
        /// </summary>
        static void UpdateSelf()
        {
            string filePath = AppDomain.CurrentDomain.BaseDirectory + "AutoUpdate.exe",
                fileTempPath = AppDomain.CurrentDomain.BaseDirectory + "AutoUpdate.exe.tmp",
                batPath = AppDomain.CurrentDomain.BaseDirectory + "AutoUpdate.bat";
            if (!File.Exists(fileTempPath))
                return;
            File.WriteAllText(batPath, string.Format(@"{0}
{1}
{2}",
"del " + filePath,
"ren " + fileTempPath + " AutoUpdate.exe",
"del " + batPath));
            Process.Start(batPath);
        }
    }
}
